import { devtools, persist } from "zustand/middleware";
import { create } from "zustand";
import { TokenI, UserI } from "@/models/user";

interface UserState {
  userMe: UserI;
  setUser: (data: UserI) => void;
  clear: () => void;
}

interface TokenState {
  credentials: TokenI;
  setCredentials: (data: TokenI) => void;
  logout: () => void;
}

export const useUserMe = create<UserState>()(
  devtools(
    persist(
      (set) => ({
        userMe: null,
        setUser: (data) => set(() => ({ userMe: data })),
        clear: () => set(() => ({ userMe: null })),
      }),
      {
        name: "user-storage",
      }
    )
  )
);

export const useToken = create<TokenState>()(
  devtools(
    persist(
      (set) => ({
        credentials: null,
        setCredentials: (data) => set(() => ({ credentials: data })),
        logout: () => {
          set(() => ({ credentials: null }));
          useUserMe.getState().clear();
        },
      }),
      {
        name: "token-storage",
      }
    )
  )
);
